package com.li.optional;

import org.junit.Test;

import javax.lang.model.element.NestingKind;
import javax.swing.text.html.Option;
import java.util.Optional;

/**
 * @author 喂S别闹
 * @create 2022/4/21-13:53
 * @Version 1.0
 * @Description: optional的测试
 */
public class OptionalTest {
    /**
     * optional.of(T t) 创建一个optional实例  t必须非空
     * optional.empty()  创建一个空的optional实例
     * optional.ofNullable(T t)  t可以为null
     */
    @Test
    public void test1() {
        Girl girl = new Girl();
        girl = null;
        Optional<Girl> girl1 = Optional.of(girl);
    }

    @Test
    public void test2() {
        Girl girl = new Girl();
        Optional<Girl> girl1 = Optional.ofNullable(girl);
        System.out.println(girl1);
    }

    //    以前
    public String getGirlName(Boy boy) {
        return boy.getGirl().getName();
    }

    @Test
    public void test3() {
        Boy boy = new Boy();
        String girlName = getGirlName(boy);
        System.out.println(girlName);
    }

    //    优化后：
    public String getGirlName1(Boy boy) {
        if (boy != null) {
            Girl girl = boy.getGirl();
            if (girl != null) {
                return girl.getName();
            }
        }
        return null;
    }

    @Test
    public void test4() {
        Boy boy = new Boy();
        String girlName = getGirlName1(boy);
        System.out.println(girlName);
    }

    //    使用Optional
    public String getGirlName2(Boy boy) {
        Optional<Boy> boyOptional = Optional.ofNullable(boy);
//    orElse(T t1):如果当前的Optional内部封装的t是非空，则返回内部的t
//        如果内部的t是空的，则返回orElse（）方法中的参数t1
        Boy boy1 = boyOptional.orElse(new Boy(new Girl("这是orelse")));
        Girl girl = boy1.getGirl();

        Optional<Girl> girl1 = Optional.ofNullable(girl);
        Girl girlelse = girl1.orElse(new Girl("girlelse"));
        return girlelse.getName();
    }

    @Test
    public void test5() {
        Boy boy = null;
        String girlName = getGirlName2(boy);
        System.out.println(girlName);
    }
}
